package com.h3c.nem.utils;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;

import com.h3c.nem.model.ai.req.AIReq;
import com.h3c.nem.model.ai.resp.AIResp;
import com.h3c.nem.model.ai.resp.BaseResp;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * @Author fys4625
 * @Date 2023/8/14 14:50
 * @Description:
 * @Version 1.0
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class AiUtil {



    @Value("${ai.tokenUrl}")
    private String tokenUrl;

    @Value("${ai.gpt35Url}")
    private String gpt35Url;
    @Value("${ai.account}")
    private String account;

    @Value("${ai.password}")
    private String password;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 获取token
     * token带Bearder
     * @return
     */
    public String getToken(){
        String tokenFromRedis = RedisUtil.get(Constants.ai.AI_TOKEN_KEY);
        if (StringUtils.hasText(tokenFromRedis)) {
            return tokenFromRedis;
        }
        try {
            Map<String, String> body = Maps.newHashMap();
            body.put("account", account);
            body.put("password", password);
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.APPLICATION_JSON);
            httpHeaders.add("Auth-Type", "DB");
            HttpEntity<Map<String, String>> entity = new HttpEntity<>(body, httpHeaders);
            ResponseEntity<JSONObject> resp = restTemplate.exchange(tokenUrl, HttpMethod.POST, entity, JSONObject.class);
            if (!HttpStatus.OK.equals(resp.getStatusCode())) {
                log.error("获取AI接口token失败：：{}", resp);
            }
            JSONObject body1 = resp.getBody();
            if (body1 == null || !Constants.ai.SUCCESS_CODE.equals(body1.getInteger("code"))) {
                log.error("获取AI接口token失败：：{}", resp);
                throw new AppBusinessException("获取AI接口token失败");
            }
            RedisUtil.setEx(Constants.ai.AI_TOKEN_KEY, body1.getString("token"), 30, TimeUnit.MINUTES);
            return body1.getString("token");
        } catch (Exception ex) {
            log.error(ex.toString());
            throw new AppBusinessException("获取AI接口token失败");
        }
    }

    /**
     * AI助手-gpt3.5模型
     * @param req
     * @return
     */
    public AIResp gpt35(AIReq req){
        String token = getToken();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.set(HttpHeaders.AUTHORIZATION, token);

        HttpEntity<AIReq> reqEntity = new HttpEntity<>(req, httpHeaders);
        ParameterizedTypeReference<BaseResp<AIResp>> reference = new ParameterizedTypeReference<BaseResp<AIResp>>() {
        };
        ResponseEntity<BaseResp<AIResp>> resp = restTemplate.exchange(gpt35Url, HttpMethod.POST, reqEntity, reference);
        if (!HttpStatus.OK.equals(resp.getStatusCode())) {
            log.error("调用AI助手失败：：{}", resp);
        }
        BaseResp<AIResp> body = resp.getBody();
        if (body == null || !Constants.ai.SUCCESS_CODE.equals(body.getCode())) {
            log.error("调用AI助手失败：：{}", resp);
            throw new AppBusinessException("调用AI助手失败");
        }
        return body.getData();

    }

}
